package com.powernode.ssm.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.powernode.ssm.config.DynamicDataSourceConfigLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;

/**
 * 动态数据源工具类
 */
@Component
public class DynamicDataSourceUtil {

    @Autowired
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Autowired
    private DynamicDataSourceConfigLogger dataSourceConfigLogger;


    /**
     * 获取所有数据源名称
     */
    public Set<String> getDataSourceNames() {
        return dynamicRoutingDataSource.getDataSources().keySet();
    }

    /**
     * 获取数据源连接（自动管理事务）
     */
    public Connection getConnection(String dataSourceName) throws SQLException {
        DataSource dataSource = dynamicRoutingDataSource.getDataSource(dataSourceName);
        if (dataSource instanceof DruidDataSource) {
            ((DruidDataSource) dataSource).setTestOnBorrow(true); // 借用时检测连接有效性
        }
        return DataSourceUtils.getConnection(dataSource);
    }

    /**
     * 获取数据源驱动类名
     */
    public String getDriverClassName(String dataSourceName) {
        return dataSourceConfigLogger.getDriverClassName(dataSourceName);
    }

    /**
     * 获取数据源驱动类名
     */
    public String getURL(String dataSourceName) {
        return dataSourceConfigLogger.getURL(dataSourceName);
    }

}